<template>
  <a-card class="invoice-management-card" title="发票管理">
    <template #extra>
      <a-space>
        <a-button size="small" @click="refreshData">
          <template #icon>
            <icon-refresh />
          </template>
          刷新
        </a-button>
        <a-button size="small" type="primary" @click="showAddModal" v-perm="['lindi:tradeApplicationInvoice:add']">
          <template #icon>
            <icon-plus />
          </template>
          添加发票
        </a-button>
      </a-space>
    </template>

    <!-- 发票列表 -->
    <div class="invoice-list">
      <div v-if="props.loading" class="loading-container">
        <a-spin size="large" />
      </div>
      
      <div v-else-if="tableData.length === 0" class="empty-container">
        <a-empty description="暂无发票文件" />
      </div>
      
      <div v-else class="invoice-grid">
        <div v-for="invoice in tableData" :key="invoice.invoiceId" class="invoice-item">
          <a-card class="invoice-card" hoverable>
            <div class="invoice-header">
              <div class="invoice-icon">
                <a-avatar :size="48" class="bg-green-100" shape="square">
                  <icon-file-pdf class="text-green-600" />
                </a-avatar>
              </div>
              <div class="invoice-info">
                <div class="invoice-title">{{ invoice.invoiceNumber || '发票文件' }}</div>
                <div class="invoice-meta">
                  <span class="invoice-type">{{ getInvoiceTypeText(invoice.invoiceType) }}</span>

                </div>
              </div>
            </div>
            
            <div class="invoice-details">
              <div class="detail-row">
                <span class="detail-label">发票编号：</span>
                <span class="detail-value">{{ invoice.invoiceNumber || '-' }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">发票类型：</span>
                <span class="detail-value">{{ getInvoiceTypeText(invoice.invoiceType) || '-' }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">发票金额：</span>
                <span class="detail-value amount">{{ invoice.invoiceMoney || '-' }}</span>
              </div>
              <div class="detail-row">
                <span class="detail-label">开票日期：</span>
                <span class="detail-value">{{ invoice.invoiceDate || '-' }}</span>
              </div>
            </div>
            
            <div class="invoice-actions">
              <a-space>
                <a-button size="mini" @click="viewInvoice(invoice)">
                  <template #icon>
                    <icon-eye />
                  </template>
                  查看
                </a-button>
                <a-button size="mini" type="primary" @click="downloadInvoice(invoice)">
                  <template #icon>
                    <icon-download />
                  </template>
                  下载
                </a-button>
                <a-button size="mini" @click="editInvoice(invoice)" v-perm="['lindi:tradeApplicationInvoice:update']">
                  <template #icon>
                    <icon-edit />
                  </template>
                  编辑
                </a-button>
                <a-button 
                  v-if="invoice.status === 'pending'"
                  size="mini" 
                  status="success" 
                  @click="verifyInvoice(invoice)"
                  v-perm="['lindi:tradeApplicationInvoice:update']"
                >
                  <template #icon>
                    <icon-check />
                  </template>
                  验证
                </a-button>
                <a-button size="mini" status="danger" @click="deleteInvoice(invoice)" v-perm="['lindi:tradeApplicationInvoice:delete']">
                  <template #icon>
                    <icon-delete />
                  </template>
                  删除
                </a-button>
              </a-space>
            </div>
          </a-card>
        </div>
      </div>
      
      <!-- 分页 -->

    </div>

    <!-- 新增/编辑发票弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      width="700px"
      @ok="handleSubmit"
      @cancel="handleModalCancel"
      @close="handleModalCancel"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="invoiceNumber" label="发票号码" required>
              <a-input v-model="formData.invoiceNumber" placeholder="请输入发票号码" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="invoiceType" label="发票类型" required>
              <a-select v-model="formData.invoiceType" placeholder="请选择发票类型">
                <a-option
                  v-for="(d, index) in dicts[proxy.DICT.lindiTradeApplicationInvoice]"
                  :key="index"
                  :label="d.dictValue"
                  :value="d.dictKey"
                />
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item field="invoiceMoney" label="发票金额(万元)" required>
              <a-input
                v-model="formData.invoiceMoney"
                placeholder="请输入发票金额"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item field="invoiceDate" label="开票日期">
              <a-date-picker
                v-model="formData.invoiceDate"
                style="width: 100%"
                placeholder="请选择开票日期"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
              />
            </a-form-item>
          </a-col>
        </a-row>

        
        <a-form-item field="invoiceFile" label="发票文件">
          <div class="file-upload-container">
            <!-- 已有附件展示区域 -->
            <div v-if="existingFiles.length > 0" class="existing-files-container mb-4">
              <div class="mb-2 flex items-center justify-between">
                <div class="text-gray-500">
                  <icon-info-circle class="mr-1" /> 已上传发票文件
                </div>
              </div>
              <a-list :bordered="false" :grid="{ gutter: 16, column: 3 }">
                <a-list-item v-for="(file, index) in existingFiles" :key="file.fileId">
                  <a-card class="file-card" hoverable>
                    <div class="flex items-start">
                      <div class="file-icon mr-3">
                        <a-avatar :size="40" shape="square">
                          <icon-file-pdf v-if="file.fileType === 'pdf'"/>
                          <icon-file-image v-else-if="['jpg', 'png', 'jpeg'].includes(file.fileType)"/>
                          <icon-file v-else/>
                        </a-avatar>
                      </div>
                      <div class="flex-1 overflow-hidden">
                        <div class="font-medium truncate mb-1">{{ file.fileName }}</div>
                        <div class="text-gray-500 text-xs mb-1">上传时间：{{ file.uploadTime || '未知' }}</div>
                        <div class="mt-2">
                          <a-space>
                            <a-button size="mini" type="primary" @click="downloadFile(file)">
                              下载
                            </a-button>
                            <a-button size="mini" @click="previewFile(file)">
                              预览
                            </a-button>
                            <a-button size="mini" status="danger" @click="removeExistingFile(index)">
                              删除
                            </a-button>
                          </a-space>
                        </div>
                      </div>
                    </div>
                  </a-card>
                </a-list-item>
              </a-list>
            </div>

            <uploadFile
              ref="invoiceUploadFileRef"
              :file-source="fs"
              :limit="1"
              :multiple="false"
              accept=".pdf,.jpg,.png,.jpeg"
              list-type="text"
              source-type="proxy"
              @upload-success="handleUploadSuccess"
            />
          </div>
        </a-form-item>

      </a-form>
    </a-modal>

    <!-- 发票验证弹窗 -->
    <a-modal
      v-model:visible="verifyModalVisible"
      title="发票验证"
      width="500px"
      @ok="handleVerify"
      @cancel="verifyModalVisible = false"
    >
      <a-form
        ref="verifyFormRef"
        :model="verifyForm"
        :rules="verifyRules"
        layout="vertical"
      >
        <a-form-item field="verifyResult" label="验证结果" required>
          <a-radio-group v-model="verifyForm.verifyResult">
            <a-radio value="verified">验证通过</a-radio>
            <a-radio value="failed">验证失败</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="verifyComment" label="验证说明">
          <a-textarea
            v-model="verifyForm.verifyComment"
            :auto-size="{ minRows: 3, maxRows: 5 }"
            placeholder="请输入验证说明"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup>
import { onMounted, reactive, ref, computed, getCurrentInstance } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import {
  IconRefresh,
  IconPlus,
  IconEye,
  IconEdit,
  IconDelete,
  IconDownload,
  IconCheck,
  IconFile,
  IconFileImage,
  IconFilePdf,
  IconInfoCircle
} from '@arco-design/web-vue/es/icon';
import uploadFile from '~/components/uploadFile/index.vue';
import { fileSource } from '~/utils/sys.js';
import {
  addTradeApplicationInvoiceApi,
  deleteTradeApplicationInvoiceByTradeApplicationInvoiceIdApi,
  updateTradeApplicationInvoiceByTradeApplicationInvoiceIdApi,
  getPageTradeApplicationInvoiceListApi,
  getTradeApplicationInvoiceByTradeApplicationInvoiceIdApi,
  getTradeApplicationInvoiceListByTradeApplicationIdApi
} from '~/api/lindi/tradeApplicationInvoice';
import { deleteFileApi } from '~/api/basic/file.js';
import { LoadDicts, DICT } from '~/utils/dict.js';

// 定义props
const props = defineProps({
  tradeApplicationId: {
    type: String,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  }
});

// 获取当前实例
const {proxy} = getCurrentInstance();

// 加载字典
const dicts = proxy.LoadDicts([DICT.lindiTradeApplicationInvoice]);

// 响应式数据
// const loading = ref(false); // 使用父组件传递的loading状态
const modalVisible = ref(false);
const verifyModalVisible = ref(false);
const modalTitle = ref('添加发票');
const formRef = ref(null);
const verifyFormRef = ref(null);
const invoiceUploadFileRef = ref(null);
const tableData = ref([]);
const editingInvoice = ref(null);
const verifyingInvoice = ref(null);
const fileList = ref([]);
const existingFiles = ref([]);
const newUploadedFileIds = ref([]); // 跟踪新上传的文件ID，用于取消时清理

// 文件来源配置
const fs = fileSource.lindi_trade_invoice_file?.key || 'lindi_trade_application_invoice_file';



// 发票统计
const summary = computed(() => {
  const totalCount = tableData.value.length;
  const totalAmount = tableData.value.reduce((sum, item) => sum + (item.amount || 0), 0);
  const verifiedCount = tableData.value.filter(item => item.status === 'verified').length;
  const pendingCount = tableData.value.filter(item => item.status === 'pending').length;
  
  return {
    totalCount,
    totalAmount: totalAmount.toFixed(2),
    verifiedCount,
    pendingCount
  };
});

// 表格列配置
const columns = [
  {
    title: '发票号码',
    dataIndex: 'invoiceNumber',
    width: 150
  },
  {
    title: '发票类型',
    dataIndex: 'invoiceType',
    slotName: 'invoiceType',
    width: 120
  },
  {
    title: '发票金额',
    dataIndex: 'amount',
    slotName: 'amount',
    width: 100
  },
  {
    title: '开票日期',
    dataIndex: 'issueDate',
    width: 120
  },
  {
    title: '销售方',
    dataIndex: 'seller',
    ellipsis: true,
    tooltip: true,
    width: 150
  },
  {
    title: '购买方',
    dataIndex: 'buyer',
    ellipsis: true,
    tooltip: true,
    width: 150
  },
  {
    title: '状态',
    dataIndex: 'status',
    slotName: 'status',
    width: 100
  },
  {
    title: '操作',
    slotName: 'actions',
    width: 280,
    fixed: 'right'
  }
];

// 表单数据
const formData = reactive({
  invoiceId: null,
  tradeApplicationId: props.tradeApplicationId,
  invoiceFileId: null,
  invoiceFile: null,
  invoiceNumber: '',
  invoiceType: '',
  invoiceMoney: '',
  invoiceDate: null
});

// 验证表单数据
const verifyForm = reactive({
  verifyResult: '',
  verifyComment: ''
});

// 表单验证规则
const formRules = {
  invoiceNumber: [
    { required: true, message: '请输入发票号码' },
    { maxLength: 50, message: '发票号码不能超过50个字符' }
  ],
  invoiceType: [
    { required: true, message: '请选择发票类型' }
  ],
  invoiceMoney: [
    { required: true, message: '请输入发票金额' }
  ]
};

// 验证表单规则
const verifyRules = {
  verifyResult: [
    { required: true, message: '请选择验证结果' }
  ]
};

// 获取发票类型颜色
const getInvoiceTypeColor = (type) => {
  const colorMap = {
    'vat_special': 'blue',
    'vat_ordinary': 'green',
    'electronic': 'purple',
    'receipt': 'orange'
  };
  return colorMap[type] || 'gray';
};

// 获取发票类型文本
const getInvoiceTypeText = (type) => {
  if (!type || !dicts[proxy.DICT.lindiTradeApplicationInvoice]) {
    return '未知类型';
  }
  const dict = dicts[proxy.DICT.lindiTradeApplicationInvoice].find(d => String(d.dictKey) === String(type));
  return dict ? dict.dictValue : '未知类型';
};

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    'pending': 'orange',
    'verified': 'green',
    'failed': 'red'
  };
  return colorMap[status] || 'gray';
};

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'pending': '待验证',
    'verified': '已验证',
    'failed': '验证失败'
  };
  return textMap[status] || '未知状态';
};

// 加载数据
const loadData = async () => {
  try {
    const response = await getTradeApplicationInvoiceListByTradeApplicationIdApi(
      props.tradeApplicationId
    );
      tableData.value = response || [];
  } catch (error) {
    console.error('获取发票列表失败:', error);
    Message.error('获取发票列表失败');
  }
};

// 刷新数据
const refreshData = () => {
  loadData();
};

// 显示新增弹窗
const showAddModal = () => {
  modalTitle.value = '添加发票';
  editingInvoice.value = null;
  newUploadedFileIds.value = []; // 清空文件跟踪
  resetForm();
  modalVisible.value = true;
};

// 查看发票
const viewInvoice = (invoice) => {
  Message.info(`查看发票: ${invoice.invoiceNumber}`);
};

// 下载发票
const downloadInvoice = (invoice) => {
  if (invoice.invoiceFile && invoice.invoiceFile.fileUrl) {
    window.open(invoice.invoiceFile.fileUrl, '_blank');
    Message.success(`开始下载: ${invoice.invoiceFile.fileName}`);
  } else {
    Message.warning('发票文件不存在');
  }
};

// 编辑发票
const editInvoice = (invoice) => {
  modalTitle.value = '编辑发票';
  editingInvoice.value = invoice;
  newUploadedFileIds.value = []; // 清空文件跟踪
  
  // 映射后端字段到表单数据
  formData.invoiceId = invoice.invoiceId;
  formData.tradeApplicationId = invoice.tradeApplicationId;
  formData.invoiceFileId = invoice.invoiceFileId;
  formData.invoiceNumber = invoice.invoiceNumber;
  formData.invoiceType = invoice.invoiceType;
  formData.invoiceMoney = invoice.invoiceMoney;
  formData.invoiceDate = invoice.invoiceDate;
  
  // 设置已有附件列表
  if (invoice.invoiceFile) {
    existingFiles.value = [{
      fileId: invoice.invoiceFileId,
      fileName: invoice.invoiceFile.fileName,
      fileUrl: invoice.invoiceFile.fileUrl,
      fileType: invoice.invoiceFile.fileName.toLowerCase().split('.').pop() || 'pdf',
      uploadTime: invoice.uploadTime || '未知'
    }];
    
    // 设置上传组件的文件列表用于回显
    if (invoiceUploadFileRef.value) {
      setTimeout(() => {
        if (invoiceUploadFileRef.value && invoiceUploadFileRef.value.fileList !== undefined) {
          invoiceUploadFileRef.value.fileList = [{
            uid: invoice.invoiceId,
            name: invoice.invoiceFile.fileName,
            url: invoice.invoiceFile.fileUrl,
            status: 'done',
            response: { fileId: invoice.invoiceFileId }
          }];
        }
      }, 0);
    }
  } else {
    existingFiles.value = [];
  }
  
  modalVisible.value = true;
};

// 验证发票
const verifyInvoice = (invoice) => {
  verifyingInvoice.value = invoice;
  verifyForm.verifyResult = '';
  verifyForm.verifyComment = '';
  verifyModalVisible.value = true;
};

// 删除发票
const deleteInvoice = (invoice) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除发票「${invoice.invoiceNumber}」吗？`,
    onOk: async () => {
      try {
        const response = await deleteTradeApplicationInvoiceByTradeApplicationInvoiceIdApi(invoice.invoiceId);
        if (response.code === 200) {
          Message.success('发票删除成功');
          loadData();
        } else {
          Message.error(response.message || '删除发票失败');
        }
      } catch (error) {
        console.error('删除发票失败:', error);
        Message.error('删除发票失败');
      }
    }
  });
};

// 处理文件上传成功
const handleUploadSuccess = (response) => {
  if (response && response.fileId) {
    // 只有在新增模式下才跟踪文件ID（编辑模式下不需要跟踪，因为是替换已有文件）
    if (!editingInvoice.value) {
      newUploadedFileIds.value.push(response.fileId);
    }
    console.log('文件上传成功，文件ID:', response.fileId);
  }
};

// 预览文件
const previewFile = (file) => {
  if (file.fileUrl) {
    window.open(file.fileUrl, '_blank');
  } else {
    Message.warning('文件链接不存在');
  }
};

// 下载文件
const downloadFile = (file) => {
  if (file.fileUrl) {
    const link = document.createElement('a');
    link.href = file.fileUrl;
    link.download = file.fileName || 'download';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } else {
    Message.warning('文件链接不存在');
  }
};

// 删除已有附件
const removeExistingFile = (index) => {
  existingFiles.value.splice(index, 1);
  // 同时清空上传组件的文件列表
  if (invoiceUploadFileRef.value && invoiceUploadFileRef.value.fileList !== undefined) {
    invoiceUploadFileRef.value.fileList = [];
  }
};

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async (errors) => {
    if (errors) {
      return;
    }
    
    // 准备提交数据
    const submitData = {
      ...formData,
      tradeApplicationId: String(props.tradeApplicationId)
    };
    
    // 处理日期格式转换
    if (submitData.invoiceDate) {
      // 如果日期是字符串格式（yyyy-MM-dd），转换为 yyyy-MM-dd HH:mm:ss 格式
      if (typeof submitData.invoiceDate === 'string' && submitData.invoiceDate.length === 10) {
        submitData.invoiceDate = submitData.invoiceDate + ' 00:00:00';
      } else if (submitData.invoiceDate instanceof Date) {
        // 如果是Date对象，格式化为 yyyy-MM-dd HH:mm:ss
        const year = submitData.invoiceDate.getFullYear();
        const month = String(submitData.invoiceDate.getMonth() + 1).padStart(2, '0');
        const day = String(submitData.invoiceDate.getDate()).padStart(2, '0');
        submitData.invoiceDate = `${year}-${month}-${day} 00:00:00`;
      }
    }
    
    // 处理文件上传
    if (invoiceUploadFileRef.value && invoiceUploadFileRef.value.fileList && invoiceUploadFileRef.value.fileList.length > 0) {
      const file = invoiceUploadFileRef.value.fileList[0];
      if (file && file.response && file.response.fileId) {
        submitData.invoiceFileId = file.response.fileId;
      } else if (file && file.uid && existingFiles.value.length > 0) {
        // 使用已有文件
        submitData.invoiceFileId = existingFiles.value[0].fileId;
      }
    } else {
      // 如果没有新上传的文件，但有已有文件，使用已有文件的ID
      if (existingFiles.value.length > 0) {
        submitData.invoiceFileId = existingFiles.value[0].fileId;
      }
    }
    
    // 如果仍然没有获取到文件ID，尝试使用getUploadFileId方法
    if (!submitData.invoiceFileId && invoiceUploadFileRef.value) {
      const uploadFileIds = invoiceUploadFileRef.value.getUploadFileId();
      if (uploadFileIds) {
        // getUploadFileId返回逗号分隔的字符串，取第一个
        const fileIdArray = uploadFileIds.split(',').filter(Boolean);
        if (fileIdArray.length > 0) {
          submitData.invoiceFileId = fileIdArray[0];
        }
      }
    }
    
    if (!submitData.invoiceFileId && !editingInvoice.value) {
      Message.error('请上传发票文件');
      return;
    }
    
    try {
      // 准备提交数据
      const finalSubmitData = {
        ...submitData,
        invoiceFileId: submitData.invoiceFileId ? String(submitData.invoiceFileId) : null
      };
      
      let response;
      if (editingInvoice.value) {
        // 编辑模式
        response = await updateTradeApplicationInvoiceByTradeApplicationInvoiceIdApi(finalSubmitData);
      } else {
        // 新增模式
        response = await addTradeApplicationInvoiceApi(finalSubmitData);
      }
      console.log(response)
      
      if (response.code === 200) {
        Message.success(editingInvoice.value ? '发票更新成功' : '发票添加成功');
        // 如果是新增模式，清空新上传文件跟踪，因为已经保存成功
        if (!editingInvoice.value) {
          newUploadedFileIds.value = [];
        }
        modalVisible.value = false;
        resetForm();
        loadData();
      } else {
        Message.error(response.message || '操作失败');
      }
    } catch (error) {
      console.error('提交发票失败:', error);
      Message.error('操作失败');
    }
  });
};

// 处理验证
const handleVerify = () => {
  verifyFormRef.value.validate((errors) => {
    if (errors) {
      return;
    }
    
    // 模拟API调用
    setTimeout(() => {
      Message.success('验证完成');
      verifyModalVisible.value = false;
      loadData();
    }, 500);
  });
};

// 处理模态框取消/关闭事件
const handleModalCancel = async () => {
  // 清理新上传但未保存的文件
  await cleanupUnusedFiles();
  // 重置表单
  resetForm();
};

// 清理未使用的文件
const cleanupUnusedFiles = async () => {
  if (newUploadedFileIds.value.length > 0) {
    try {
      // 删除所有新上传但未保存的文件
      for (const fileId of newUploadedFileIds.value) {
        await deleteFileApi(fileId);
      }
      console.log('已清理未保存的文件:', newUploadedFileIds.value);
    } catch (error) {
      console.error('清理文件失败:', error);
    } finally {
      newUploadedFileIds.value = [];
    }
  }
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(formData, {
    invoiceId: null,
    tradeApplicationId: props.tradeApplicationId,
    invoiceFileId: null,
    invoiceFile: null,
    invoiceNumber: '',
    invoiceType: '',
    invoiceMoney: '',
    invoiceDate: null
  });
  fileList.value = [];
  existingFiles.value = [];
  newUploadedFileIds.value = [];
  editingInvoice.value = null;
  
  // 清空上传组件的文件列表
  if (invoiceUploadFileRef.value && invoiceUploadFileRef.value.fileList !== undefined) {
    invoiceUploadFileRef.value.fileList = [];
  }
};



// 组件挂载时加载数据
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.invoice-management-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.invoice-summary {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 16px;
}

.mb-4 {
  margin-bottom: 16px;
}

.font-medium {
  font-weight: 500;
}

.invoice-list {
  margin-top: 24px;
}

.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #666;
}

.empty-container {
  padding: 60px 20px;
  text-align: center;
}

.invoice-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 16px;
}

.invoice-item {
  width: 100%;
}

.invoice-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.invoice-card :deep(.arco-card-body) {
  padding: 16px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.invoice-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
}

.invoice-icon {
  margin-right: 12px;
  flex-shrink: 0;
}

.invoice-info {
  flex: 1;
  min-width: 0;
}

.invoice-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
  word-break: break-all;
  line-height: 1.4;
}

.invoice-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
}

.invoice-type {
  font-size: 12px;
  color: #666;
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.invoice-details {
  flex: 1;
  margin-bottom: 16px;
}

.detail-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
  font-size: 13px;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-label {
  color: #666;
  flex-shrink: 0;
  margin-right: 8px;
  font-weight: 500;
}

.detail-value {
  color: #333;
  text-align: right;
  word-break: break-all;
  flex: 1;
}

.detail-value.amount {
  color: #f53f3f;
  font-weight: 600;
}

.invoice-actions {
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;
  margin-top: auto;
}

.invoice-actions :deep(.arco-space) {
  width: 100%;
  justify-content: center;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

.bg-green-100 {
  background-color: #f0f9ff;
}

.text-green-600 {
  color: #059669;
}

.upload-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  cursor: pointer;
  transition: all 0.3s;
}

.upload-area:hover {
  border-color: #1890ff;
  background-color: #f0f8ff;
}

.upload-icon {
  font-size: 24px;
  color: #999;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.upload-tip {
  font-size: 12px;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .invoice-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .invoice-grid {
    gap: 12px;
  }
  
  .invoice-card :deep(.arco-card-body) {
    padding: 12px;
  }
  
  .invoice-title {
    font-size: 14px;
  }
  
  .detail-row {
    font-size: 12px;
  }
}
</style>